const app = getApp();
import {
  queryHomePageCarousel,
  queryHomePageSeckillProduct,
  querybestseller,
  queryHomePageTabList,
  queryHomePageProductList
} from '../../service/home-page';
import {
  querySeckillProductList
} from "../../service/seckill"
const windowInfo = wx.getWindowInfo()

Page({
  data: {
    // 胶囊距离屏幕顶部的距离
    top: app.globalData.menuButtonTop,
    // 胶囊高度
    height: app.globalData.menuButtonHeight,
    // 胶囊底部距离屏幕顶部的距离
    bottom: app.globalData.menuButtonBottom,
    // 胶囊左方大小
    left: app.globalData.menuButtonLeft,
    // 首页轮播图数据
    carouselList: null,
    // 秒杀商品信息
    seckillProductList: null,
    // 是否滑动超过一定的距离需要展示另一个tab区域
    showAnotherTab: false,
    // tab区域的商品列表
    productList: [],
    // tab 区域的当前页面
    page: 1,
    // tab区域的页面大小
    pageSize: 10,
    // 是否展示粘性布局的tab
    isShowStickyTab: false,
    // tab区域的滚动条的位置
    scrollLeft: 0,
    // 是否还有更多的数据
    hasMore: true,
    // tab列表
    tabList: [{
      categoryId: -1,
      categoryName: "猜你喜欢"
    }],
    // tab区域的激活索引
    activeTabIndex: 0,
    // 屏幕宽度
    windowWidth: windowInfo.screenWidth,
    // scroll-view 高度
    scrollViewHeight: 0,
    // tab 区域距离顶部的高度
    tabTop: -1,
    // scrollview纵向滚动的距离
    scrollTop:0,
  },
  /**
   *  点击查看商品详情
   */
  onTapCheckProduct(event) {
    const productId = event.currentTarget.dataset.productId
    wx.navigateTo({
      url: `/pages/Product/Product?productId=${productId}`,
    })
  },
  /**
   *  点击添加商品到购物车
   */
  onTapShippingCartButton(event) {
    const productId = event.currentTarget.dataset.productId
    wx.navigateTo({
      url: `/pages/Product/Product?productId=${productId}&showShippingCart=true`,
    })
  },

  /**
   *  点击Tab区域按钮
   */
  async onClickTabItem(event) {
    const index = event.currentTarget.dataset.index
    const offsetLeft = event.currentTarget.offsetLeft
    const query = wx.createSelectorQuery()
    this.setData({
      activeTabIndex: event.currentTarget.dataset.index,
      page: 1,
      pageSize: 10
    })
    query.select(`#tab-${index}`).boundingClientRect()
    query.exec((res) => {
      const {
        width
      } = res[0]
      const scrollLeft = offsetLeft + width / 2 - this.data.windowWidth / 2
      this.setData({
        scrollLeft
      })
    })
    const categoryId = this.data.tabList[this.data.activeTabIndex].categoryId
    const productList = await queryHomePageProductList(categoryId, this.data.page, this.data.pageSize)
    this.setData({
      productList: productList.data.records,
    })
  },
  /**
   * 生命周期函数
   */
  async onLoad() {
    // 轮播图
    const carouselListRes = await queryHomePageCarousel();
    // 秒杀商品
    const seckillProductInfo = await querySeckillProductList(0, 1, 4)
    // tab区域列表
    const tabsRes = await queryHomePageTabList()
    // 猜你喜欢商品列表
    const productListRes = await queryHomePageProductList(
      this.data.tabList[this.data.activeTabIndex].categoryId,
      this.data.page,
      this.data.pageSize
    )
    this.setData({
      carouselList: carouselListRes.data,
      seckillProductList: seckillProductInfo.data.records,
      tabList: [...this.data.tabList, ...tabsRes.data],
      productList: productListRes.data.records
    });
    console.log(this.data);
  },
  /**
   * 上拉刷新事件
   */
  async loadMoreData() {
    this.data.page = this.data.page + 1
    const productListRes = await queryHomePageProductList(
      this.data.tabList[this.data.activeTabIndex].categoryId,
      this.data.page,
      this.data.pageSize
    )
    this.setData({
      productList: [...this.data.productList, ...productListRes.data.records]
    })
  },
  /**
   * 点击搜索框
   */
  onTapSearchBox() {
    wx.navigateTo({
      url: '/pages/Search/Search',
    });
  },

  // 点击查看轮播图
  onTapCheckCarouselProduct(event) {
    console.log(event);
    const productId = event.currentTarget.dataset.productId;
    wx.navigateTo({
      url: `/pages/Product/Product?productId=${productId}`,
    });
  },
  /**
   * 点击秒杀商品
   */
  onTapSeckillProduct(event) {
    const productId = event.currentTarget.dataset.productId;
    console.log(productId);
    wx.navigateTo({
      url: `/pages/Product/Product?productId=${productId}`,
    });
  },
  /**
   * 点击查看更多秒杀商品
   */
  onTapFindMoreSeckillProduct() {
    wx.navigateTo({
      url: '/pages/SeckillPage/SeckillPage',
    });
  },

  /**
   * home-page 处理滑动函数
   */
  handlerScroll(event) {
    this.judgeTabVisibility(event)
  },
  /**
   * 点击热销排行榜
   */
  onTapHotSalesRanking() {
    wx.navigateTo({
      url: '/pages/HotSalesRanking/HotSalesRanking',
    });
  },
  /**
   * 点击领券专区
   */
  onTapCouponCollectionArea() {
    wx.navigateTo({
      url: '/pages/CouponCollectionArea/CouponCollectionArea',
    });
  },
  /**
   * 点击积分商城
   */
  onTapPointsMall() {
    wx.navigateTo({
      url: '/pages/PointsMall/PointsMall',
    });
  },
  /**
   * 点击限时秒杀
   */
  onTapSeckill() {
    wx.navigateTo({
      url: '/pages/SeckillPage/SeckillPage',
    });
  },
  /**
   * 点击常买商品
   */
  onTapFrequentlyPurchasedItems() {
    wx.navigateTo({
      url: '/pages/FrequentlyPurchasedItems/FrequentlyPurchasedItems',
    });
  },
  /**
   * 点击新客专区
   */
  onTapNewCustomerExclusiveArea() {
    wx.navigateTo({
      url: '/pages/NewCustomerExclusiveArea/NewCustomerExclusiveArea',
    });
  },
  /**
   * 点击临期特惠
   */
  onTapNearExpirySpecialOffer() {
    wx.navigateTo({
      url: '/pages/NearExpirySpecialOffer/NearExpirySpecialOffer',
    });
  },
  /**
   * 点击品牌专区
   */
  onTapBrandExclusiveZone() {
    wx.navigateTo({
      url: '/pages/BrandExclusiveZone/BrandExclusiveZone',
    });
  },
  onReady() {
    this.judgeTabVisibility()
    const query = wx.createSelectorQuery()
    query.select("#home-body-seckill").boundingClientRect()
    query.exec((res)=>{
      console.log(res);
      this.data.scrollTop = res[0].top
    })
  },
  // 查询tab是否已经滑出了scroll-view区域
  judgeTabVisibility(event) {
    const query = wx.createSelectorQuery().in(this);
    query
      .select("#home-page-scroll-view")
      .boundingClientRect((scrollViewRect) => {
        this.scrollViewRect = scrollViewRect; // 缓存 scroll-view 信息（高度、顶部距离）
      })
      .select("#home-body-tab")
      .boundingClientRect((elementRect) => {
        this.elementRect = elementRect; // 缓存目标元素信息（高度、顶部距离）
      })
      .select("#home-page-scroll-view")
      .boundingClientRect((scrollOffset) => {
        this.scrollTop = scrollOffset.top; // scroll-view 内部滚动距离（scroll-top）
      })
      .exec(() => {
        this.calculateVisibility(event);
      })
  },
  calculateVisibility(event) {
    const {
      scrollViewRect,
      elementRect,
      scrollTop
    } = this;
    const {
      height: scrollViewHeight
    } = scrollViewRect; // scroll-view 可视高度
    const {
      top: elementTop,
      height: elementHeight
    } = elementRect; // 元素顶部距离、自身高度

    // 关键计算：元素相对于 scroll-view 可视区域的位置
    const elementBottom = elementTop + elementHeight; // 元素底部距离 scroll-view 顶部的距离
    const viewportBottom = scrollTop + scrollViewHeight; // scroll-view 可视区域底部（滚动后）
    let status = "";
    // 1. 完全滑出（顶部）：元素底部 < 滚动条顶部
    if (elementBottom < scrollTop) {
      status = "顶部滑出";
      this.setData({
        showAnotherTab: true
      })
     
    }
    // 2. 完全滑出（底部）：元素顶部 > 可视区域底部
    else if (elementTop > viewportBottom) {
      status = "底部滑出";
    }
    // 3. 完全可见：元素顶部 >= 滚动条顶部，且元素底部 <= 可视区域底部
    else if (elementTop >= scrollTop && elementBottom <= viewportBottom) {
      status = "完全可见";
      this.setData({
        showAnotherTab: false
      })
    }
    // 4. 部分可见（未完全滑出）
    else {
      status = "部分可见";
      this.setData({
        showAnotherTab: true,
      })
    }
  }

});